<!DOCTYPE html>
<html lang=en>
<head>
  {% include "header.html" %}
  <script src="/site_media/js/play_handling.js"></script>
</head>
<body>
	{% include "topbar.html" %}
	<div class="container">
		<div class="content">
			<div class="row">
				<div class="span3 fadebgbright" style="height: 600px;padding: 5px">
				  <div style="padding: 0px;">
				    <ul class="thumbnails" style="margin-left: -20px; height: 120px">
              <li id="profile-pic-thumbnail" class="thumbnail" style="width: 95px; height: 110px; margin-bottom: 0px">
                <div class='label-square-bottom label-info username_of_{{ profile.id }} wordwrap' style='width:90px;padding-right: 2px;z-index: 1;position: absolute;'>
                  {{ profile.name }}
                </div>
                <div style="height: 95px;width: 95px; background-color: gray;margin-top: 13px">
                <img id="profile" class="game-avatar avatar_of_{{ profile.id }}" src="{{ profile.getAvatar }}"></img>
                </div>
              </li>
              <li>
                <table cellpadding=2px>
			            <tr><td><span class='label'>Score</span></td><td><span id='score_of_{{profile.id}}' class='label label-success'>0</span></td></tr>
			            <tr><td><span class='label'>Won</span></td><td><span id='won_of_{{profile.id}}' class='label label-success'>0</span></td></tr>
			            <tr><td colspan="2">
			              <span name="playing_span" id="playing_of_{{profile.id}}" class='label label-important' style="opacity:0.0">Turn&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span>
			            </td></tr>
			            <tr><td colspan="2">
			              <span name="lead_span" id="lead_of_{{profile.id}}" class='label label-success' style="opacity:0.0">Lead&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span>
			            </td></tr>
			            <tr><td colspan="2">
			              <span name="dealer_span" id="dealer_of_{{profile.id}}" class='label label-warning' style="opacity:0.0">Dealer&nbsp&nbsp&nbsp&nbsp</span>
			            </td></tr>
			          </table>
              </li>
            </ul>
				  </div>
				  <div>{% include "chat.html" %}</div>
				</div>
				<div id="game_area" class="span9 rounded" style="height: 600px; padding: 5px; width: 665px">
				  <div class="row" style="margin-left: -40px;margin-right: -15px">
				    <div class="span3" style="height: 195px">
					    <ul class="thumbnails">
	              <li class="thumbnail fadebg player_pos 3-player-2 5-player-3 6-player-4 hide" style="width: 175px;"></li>
	            </ul>
            </div>
						<div class="span3" style="height: 195px">
						  <ul class="thumbnails">
                <li class="thumbnail fadebg player_pos 4-player-2 2-player-1 6-player-3 hide" style="width: 175px;"></li>
              </ul>
						</div>
						<div class="span3" style="height: 195px;">
						  <ul class="thumbnails">
                <li class="thumbnail fadebg player_pos 3-player-1 5-player-2 6-player-2 hide" style="width: 175px;"></li>
              </ul>
            </div>
					</div>
		      <div class="row" style="margin-left: -40px;margin-right: -15px">
		        <div class="span3" style="height: 195px">
		          <ul class="thumbnails">
                <li class="thumbnail fadebg player_pos 4-player-3 5-player-4 6-player-5 hide" style="width: 175px;"></li>
              </ul>
            </div>
			      <div class="span3" style="height: 195px;">
			        <div id="board" class="board">
                <img id="current_card_image" src="/site_media/images/cards/back.png"
                  alt="" style="opacity:0;height: 9.5em;width: auto; margin-left: -50px">
              </div>
              <div id="played_thumbnail_div"
                style="height: 60px;width:auto; margin-left: 18px;padding-bottom: 0px;margin-top: 0px">
                <div class="self-played-card-holder" style="display: inline-block;text-align: center;" rel="0">
                  <div id="dried-card-{{ profile.id }}-0" class='fadebgdark hide dry_banner' style="z-index: 1;position: absolute; margin-top: 35px;width: 34px">
                    <i class="icon-eye-close icon-white"></i>
                  </div>
                  <br/>
                  <img id="played-card-{{ profile.id }}-0" class="self-played_card played_card thumbnail-mini"
                    style="opacity:0.1;width:31px;height:48px;"
                    src="/site_media/images/cards/back.png">
                </div>
                <div class="self-played-card-holder" style="display: inline-block;text-align: center;" rel="1">
                  <div id="dried-card-{{ profile.id }}-1" class='fadebgdark hide dry_banner' style="z-index: 1;position: absolute; margin-top: 35px;width: 34px">
                    <i class="icon-eye-close icon-white"></i>
                  </div>
                  <br/>
                  <img id="played-card-{{ profile.id }}-1" class="self-played_card played_card thumbnail-mini"
                    style="opacity:0.1;width:31px;height:48px;"
                    src="/site_media/images/cards/back.png">
                </div>
                <div class="self-played-card-holder" style="display: inline-block;text-align: center;" rel="2">
                  <div id="dried-card-{{ profile.id }}-2" class='fadebgdark hide dry_banner' style="z-index: 1;position: absolute; margin-top: 35px;width: 34px">
                    <i class="icon-eye-close icon-white"></i>
                  </div>
                  <br/>
                  <img id="played-card-{{ profile.id }}-2" class="self-played_card played_card thumbnail-mini"
                    style="opacity:0.1;width:31px;height:48px;"
                    src="/site_media/images/cards/back.png">
                </div>
                <div class="self-played-card-holder" style="display: inline-block;text-align: center;" rel="3">
                  <div id="dried-card-{{ profile.id }}-3" class='fadebgdark hide dry_banner' style="z-index: 1;position: absolute; margin-top: 35px;width: 34px">
                    <i class="icon-eye-close icon-white"></i>
                  </div>
                  <br/>
                  <img id="played-card-{{ profile.id }}-3" class="self-played_card played_card thumbnail-mini"
                    style="opacity:0.1;width:31px;height:48px;"
                    src="/site_media/images/cards/back.png">
                </div>
                <div class="self-played-card-holder" style="display: inline-block;text-align: center;" rel="4">
	                <div id="dried-card-{{ profile.id }}-4" class='fadebgdark hide dry_banner' style="z-index: 1;position: absolute; margin-top: 35px;width: 34px">
	                  <i class="icon-eye-close icon-white"></i>
	                </div>
	                <br/>
	                <img id="played-card-{{ profile.id }}-4" class="self-played_card played_card thumbnail-mini"
	                  style="opacity:0.1;width:31px;height:48px;"
	                  src="/site_media/images/cards/back.png">
                </div>
              </div>
	          </div>
	          <div class="span3" style="height: 195px">
	            <ul class="thumbnails">
                <li class="thumbnail fadebg player_pos 4-player-1 5-player-1 6-player-1 hide" style="width: 175px;"></li>
              </ul>
            </div>
		      </div>
				  <div class="row" style="margin-left: -40px;margin-right: -15px">
						<div class="span4 offset3">
		          {% include "hand.html" %}
		        </div>
		      </div>
		      <div class="row">
		      <div id="spar_actions" class="span7 offset2">
		        <button id="drop_card" class="btn btn-small btn-primary" disabled="disabled"
		          style="width: 90px;text-align: left;"><i class="icon-share-alt icon-white"></i>&nbsp&nbspPlay</button>
            <button id="dry_button" class="btn btn-small btn-info" disabled="disabled"
              style="width: 90px;text-align: left;"><i class="icon-eye-close icon-white"></i>&nbsp&nbspDry</button>
            <button id="show_dry_button" class="btn btn-small btn-info" disabled="disabled"
              style="width: 90px;text-align: left;"><i class="icon-eye-open icon-white"></i>&nbsp&nbspShow Dry</button>
            <button id="under_ten_button" class="btn btn-small btn-info" disabled="disabled"
              style="width: 90px;text-align: left;"><i class="icon-flag icon-white"></i>&nbsp&nbspUnder 10</button>
            <button id="deal_button" class="btn btn-info btn-small hide"
              style="width: 100px; text-align: left">
              <i class="icon-refresh icon-white"></i>&nbsp&nbspDeal Cards</button>
            <button id="ready_button" class="btn btn-success btn-small hide"
              style="width: 50px; margin-left: -215px;margin-top: -80px">Ready</button>
		      </div>
		      </div>
				</div>
			</div>
		</div>
	</div>
	<div name="player-stats-div" class="hide">
	<table cellpadding=0px>
      <tr>
	      <td>
	        <div name="avatar-div"></div>
	      </td>
	      <td style="vertical-align: top;padding-left: 2px">
	        <table cellpadding=2px>
			      <tr><td><span class='label'>Score</span></td><td><span name='score_span' class='label label-success'>0</span></td></tr>
			      <tr><td><span class='label'>Won</span></td><td><span name='won_span' class='label label-success'>0</span></td></tr>
				    <tr><td colspan="2">
				      <span name="playing_span" class='label label-important' style="opacity:0.0">Turn&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span>
				    </td></tr>
				    <tr><td colspan="2">
              <span name="lead_span" class='label label-success' style="opacity:0.0">Lead&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span>
            </td></tr>
				    <tr><td colspan="2">
				      <span name="dealer_span" class='label label-warning' style="opacity:0.0">Dealer&nbsp&nbsp&nbsp&nbsp</span>
				    </td></tr>
			    </table>
	      </td>
      </tr>
      <tr><td colspan="2"></td></tr>
		</table>
	</div>
</body>
<script>
$(document).ready(function() {
	  window.isTurn = false;
	  window.isLead = false;
	  window.alertMode = false;
	  window.dryCardNumbers = [];
	  show_loading = true;
	  $('#game_loading_modal').modal({backdrop: true, keyboard: false});
    {% load custom_filters %}
    window.playerMap = {"{{ profile.id }}": "{{ profile.name }}"};
    window.avatarMap = {"{{ profile.id }}": "{{ profile.getAvatar }}"};
    $(".self-played-card-holder").draggable({revert: true});

    window.cardPos = 0;
    window.playerCount = 0;
    window.clickedCards = Array();
    window.currentPlayer = "{{ profile.id }}";
    window.currentGame = "{{ game.id }}";
    {% for game_player in game|getOrderedActiveGamePlayersWithPlayerAtZero:profile.id %}
    	{% load custom_filters %}
      {% if game_player.player.id != profile.id %}
    	  playerCount++;
    	  {% with game_status=game_player|getMetadata:'status' player_status=game_player.player|getMetadata:'status' %}
   	    {% if game_status != 'connected' and player_status != 'connected' %}
           $(".{{ game.getActiveGamePlayers|length }}-player-" + playerCount).css("opacity", 0.5);
        {% endif %}
        loadPlayer({{ game.getActiveGamePlayers|length }}, "{{ game_player.player.id }}",
      	    "{{ game_player.player.getAvatar }}", playerCount, "{{ game_player.player.name }}",
      		  "{{ game_status }}", "{{ player_status }}");
        {% endwith %}
      {% endif %}
      {% for dry_card_index in game_player|getMetadata:'dry_card_indeces' %}
        {% with session=game|getMetadata:'session' %}
        {% with hands=game_player|getMetadata:'hand' %}
        {% with hand=hands|mapAccess:session %}
        {% if game_player.player.id != profile.id %}
          console.log("Dried: {{ hand|mapAccess:dry_card_index }}");
          processDropForBoard("back", "{{ game_player.player.id }}",
                  "{{ 4|sub:forloop.counter0 }}", "dry", {{ dry_card_index }});
        {% else %}
        {% with dry_card=hand|mapAccess:dry_card_index %}
          processDropForBoard("{{ dry_card.fileFormat }}", "{{ game_player.player.id }}",
                 "{{ 4|sub:forloop.counter0 }}", "dry", {{ dry_card_index }});
        {% endwith %}
        {% endif %}
        {% endwith %}
        {% endwith %}
        {% endwith %}
      {% endfor %}
    {% endfor %}

    {% load custom_filters %}
    {% if game|getMetadata:"dealer" == profile.id and not game|getMetadata:"in_progress" %}
      $("#deal_button").removeAttr("disabled");
	    $("#deal_button").fadeIn();
	  {% endif %}

	  {% if game|getMetadata:"turn_player" == profile.id %}
	    isTurn = true;
	  {% else %}
	    isTurn = false;
    {% endif %}

	  {% for drop in game|getGamePlaysWithType:"drop" %}
	    {% if drop|getMetadata:"session" == game|getMetadata:"session" %}
		    {% with drop|getMetadata:'cards' as cards %}
		      {% for card in cards|splitString:"," %}
		        {% with card_numbers=drop|getMetadata:'card_numbers' %}
		        {% with card_indeces=drop|getMetadata:'card_indeces' %}
		          console.log("IS THIS REAL LIFE?: {{ card }} {{ card_numbers|mapAccess:forloop.counter0 }} {{ drop.play_type }}");
		          processDropForBoard("{{ card }}", "{{ drop.player.id }}",
		        		  "{{ card_numbers|mapAccess:forloop.counter0 }}", "{{ drop.play_type }}",
		        		  {{ card_indeces|mapAccess:forloop.counter0 }});
		        {% endwith %}
		        {% endwith %}
		      {% endfor %}
		    {% endwith %}
	    {% endif %}
	  {% endfor %}

	  updateGameState();

    var onPlayerProfileUpdate = function (itemPos, updateInfo, itemName) {
        var newName = updateInfo.getNewValue("new_value");
        var oldName = updateInfo.getNewValue("old_value");
        var field = updateInfo.getNewValue("field");

        var playerId = updateInfo.getNewValue("player_id")
        if (field == "name") {
        	$(".username_of_" + playerId ).text(newName);
        	playerMap[playerId] = newName;
        }

        else if(field == "avatar") {
        	$(".avatar_of_" + playerId ).attr("src", newName);
        	avatarMap[playerId] = newName;
        }
    };

    {% include "game_players_edit_animations.js" %}

		var onConnectionItemUpdate = function (itemPos, updateInfo, itemName) {
		    var gameId = updateInfo.getNewValue("game_id")
		    var playerId = updateInfo.getNewValue("player_id")
		    var status = updateInfo.getNewValue("status");
		    if(gameId != "0" && status == "connected"){
		    	if (!(playerId in playerMap)) {
  		    	updateGamePlayers(playerId, "add");
		    	}
		    	$("#status_of_" + playerId).attr("fill", "green");
		    	$(".profile-thumbnail-" + playerId).animate({ opacity: 1.0 }, 500);
		    }
		    else if(gameId == "0" && status != "connected"){
		    	$("#status_of_" + playerId).attr("fill", "grey");
          $(".profile-thumbnail-" + playerId).animate({ opacity: 0.5 }, 500);
        }
		    else if(gameId != "0" && status != "connected" &&
		    		$("#status_of_" + playerId).attr("fill") != "grey"){
		    	$("#status_of_" + playerId).attr("fill", "#f89406");
		    	$(".profile-thumbnail-" + playerId).animate({ opacity: 1.0 }, 500);
		    }
		    else if(gameId == "0" && status == "connected" &&
		    		$("#status_of_" + playerId).attr("fill") != "green"){
		    	$("#status_of_" + playerId).attr("fill", "#f89406");
		    	$(".profile-thumbnail-" + playerId).animate({ opacity: 1.0 }, 500);
        }
		};

    $("#drop_card").click(function() {
    	alertMode = false;
    	$("#drop_card").attr("disabled", "disabled");
    	var selectedCards = new Array();
    	var selectedCardIndeces = new Array();
      var playType = "drop";
      var playSubType = "normal";

    	$.each(clickedCards, function(i, object){
    		selectedCards.push($(object).find(".card").attr("rel"));
    		selectedCardIndeces.push($(object).find(".card").attr("name"));
    	});

    	if ($(this).hasClass("dry_mode")) {
    		selectedCards.push($("#played-card-{{ profile.id }}-" + window.dryCardNumbers[0]).attr("fileFormat"));
        selectedCardIndeces.push($("#played-card-{{ profile.id }}-" + window.dryCardNumbers[0]).attr("rel"));
        playSubType = "dry";
    	}

      var metadata = ["cards:" + selectedCards.join(","), "card_indeces:" + selectedCardIndeces.join(","), "play_sub_type:" + playSubType];
      var metadataMap = {"cards": selectedCards.join(","), "card_indeces": selectedCardIndeces.join(","), "play_sub_type": playSubType};

      $.post("/makePlay/", {"play_type":playType, "game_id":'{{ game.id }}', "metadata": metadata})
	      .success(function(data) {
          var errors = data["errors"];
          if(errors && errors.length > 0) {
        	  $("#drop_card").removeAttr("disabled");
        	  alert(errors[0]);
        	  updateGameState();
          }
          else {
	          var playId = data["play_id"];
	          metadata.push("card_numbers:" + data["response"]["card_numbers"]);
	          metadata.push("message:" + data["response"]["message"]);
	          metadataMap["card_numbers"] = data["response"]["card_numbers"];
	          metadataMap["message"] = data["response"]["message"];
        	  $(".card-clicked").click();
        	  var mex = "GAME_PLAY|{{ game.id }}|{{ profile.id }}|{{ profile.name }}|" + playType + "|" + metadata.join("|");
            engineRef.sendMessage(mex, null, 5000);
        	  processDrop(metadataMap, "{{ profile.id }}", "{{ profile.name }}", playType, data["response"]["message"]);

        	  var botPlays = data["response"]["bot_plays"];
        	  if(botPlays) {
	        	  for (botPlayCounter=0; botPlayCounter<botPlays.length; botPlayCounter++) {
	        		  if(botPlays[botPlayCounter]){
	        			  var metadataString = "";
	        			  for (key in botPlays[botPlayCounter]["metadata"]) {
	        				  if(key == "card_indeces" || key == "card_numbers" || key == "cards" || key == "message") {
	        				    metadataString += key + ":" + botPlays[botPlayCounter]["metadata"][key] + "|"
	        				  }
	        			  }
	        			  var mex = "GAME_PLAY|{{ game.id }}|" + botPlays[botPlayCounter]['player_id'] + "|" +
	        			      botPlays[botPlayCounter]["player_name"] + "|" + playType + "|" + metadataString;
	        	      engineRef.sendMessage(mex, null, 5000);
	        		  }
	        	  }
        	  }
          }
	      });
    });

    $("#profile-pic-thumbnail").click(function(){
    	$("#update-profile-button").click();
    });

    $("#deal_button").click(function(){
    	$.post("/makePlay/", {"play_type":"deal", "game_id":'{{ game.id }}', "metadata": []})
    	  .success(function(data) {
          var errors = data["errors"];
          if(errors && errors.length > 0) {
            alert(errors[0]);
            updateGameState();
          }
          else {
        	  $("#deal_button").attr("disabled", "disabled");
        	  $("#deal_button").fadeOut();
        	  var mex = "GAME_PLAY|{{ game.id }}|{{ profile.id }}|{{ profile.name }}|deal|message:" +
              data["response"]["message"];
            engineRef.sendMessage(mex, null, 5000);
          }
        });
    });

    $("#ready_button").click(function(){
    	$.post("/makePlay/", {"play_type":"ready", "game_id":'{{ game.id }}', "metadata": []})
        .success(function(data) {
          var errors = data["errors"];
          if(errors && errors.length > 0) {
            alert(errors[0]);
            updateGameState();
          } else {
        	  if (isTurn) {
        	    $("#drop_card").removeAttr("disabled");
        	  }
        	  $("#ready_button").fadeOut();
        	  $("#dry_button").attr("disabled", "disabled");
            $("#show_dry_button").attr("disabled", "disabled");
            $("#under_ten_button").attr("disabled", "disabled");
            var mex = "GAME_PLAY|{{ game.id }}|{{ profile.id }}|{{ profile.name }}|ready|message:" +
                data["response"]["message"];
            engineRef.sendMessage(mex, null, 5000);
          }
        });
    });

    $("#dry_button").click(function(){
    	var selectedCards = new Array();
    	var selectedCardsForOthers = new Array();
      var selectedCardIndeces = new Array();

      $.each(clickedCards, function(i, object){
    	  selectedCards.push($(this).find(".card").attr("rel"));
    	  selectedCardsForOthers.push("back");
        selectedCardIndeces.push($(this).find(".card").attr("name"));
      });
      var playType = "dry";
      var metadata = ["cards:" + selectedCards.join(","), "card_indeces:" + selectedCardIndeces.join(",")];
      var metadataForOthers = ["cards:" + selectedCardsForOthers.join(","), "card_indeces:" + selectedCardIndeces.join(",")];
      var metadataMap = {"cards": selectedCards.join(","), "card_indeces": selectedCardIndeces.join(",")};
    	$.post("/makePlay/", {"play_type":"dry", "game_id":'{{ game.id }}', "metadata": metadata})
        .success(function(data) {
          var errors = data["errors"];
          if(errors && errors.length > 0) {
            alert(errors[0]);
            updateGameState();
          } else {
        	  console.log(data["response"]["card_numbers"]);
        	  var playId = data["play_id"];
        	  metadata.push("card_numbers:" + data["response"]["card_numbers"]);
            metadata.push("message:" + data["response"]["message"]);
            metadataForOthers.push("card_numbers:" + data["response"]["card_numbers"]);
            metadataForOthers.push("message:" + data["response"]["message"]);
            metadataMap["card_numbers"] = data["response"]["card_numbers"];
            metadataMap["message"] = data["response"]["message"];
        	  $(".card-clicked").click();
            var mex = "GAME_PLAY|{{ game.id }}|{{ profile.id }}|{{ profile.name }}|" + playType + "|" + metadataForOthers.join("|");
            engineRef.sendMessage(mex, null, 5000);
            processDrop(metadataMap, "{{ profile.id }}", "{{ profile.name }}", playType, data["response"]["message"]);
          }
        });
    });

    if (navigator.userAgent.indexOf("Firefox")!=-1) {
      $("#message_entry").css("height", "67px");
    }

    subscribeFeed(["game_chats_{{ game.id }}"], ["message","player","time", "player_id"], onItemUpdate, onEngineReady);
    subscribeFeed(["game_connect_events_{{ game.id }}"], ["player_id", "game_id", "status"], onConnectionItemUpdate, onEngineReady);
    subscribeFeed(["game_plays_{{ game.id }}"], ["player_name", "player_id", "play_type", "metadata"], onPlayItemUpdate, onEngineReady);
    subscribeFeed(["game_player_profile_updates_{{ game.id }}"], ["player_id", "field", "old_value", "new_value"], onPlayerProfileUpdate, onEngineReady);
    subscribeFeed(["game_player_connect_events_{{ game.id }}_{{ profile.id }}"], ["placeholder"], null, onEngineReady);

    {% for game_player in game.getActiveGamePlayers %}
      subscribeFeed(["player_presence_events_{{ game_player.player.id }}"], ["player_id", "game_id", "status"], onConnectionItemUpdate, onEngineReady);
    {% endfor %}
});
</script>
</html>